/*
 * @description: 
 * @Author: T.W
 * @Github: https://github.com/TernenceWu0702
 * @Date: 2021-07-23 11:46:19
 * @LastEditors: T.W
 * @LastEditTime: 2021-11-01 17:11:50
 */

/**
 * @description: 保存localStorage
 * @param {string} key 关键字
 * @param {any} value 值
 * @param {number} ttlMs 保存时间
 */
export const setLocalStorage = (key: string, value: any, ttlMs: number) => {
    const storageData = { value, expirationDate: new Date().getTime() + ttlMs };
    localStorage.setItem(key, JSON.stringify(storageData));
}

/**
 * @description: 获取localStorage
 * @param {string} key 关键字
 * @return {*} 值
 */
export const getLocalStorage = (key: string) => {
    const storageData = JSON.parse(localStorage.getItem(key) || "");
    if (storageData !== null) {
        if (storageData.expirationDate != null && storageData.expirationDate < new Date().getTime()) {
            localStorage.removeItem(key);
            return null;
        }
        return storageData.value;
    }
    return null;
}

/**
 * @description: 设置cookie
 * @param {string} key
 * @param {string} value
 * @param {number} expire
 * @return {*}
 */
export const setCookie = (key: string, value: string, expire: number) => {
    const d: Date = new Date();
    d.setDate(d.getDate() + expire);
    document.cookie = `${key}=${value};expires=${d.toUTCString()}`
};

/**
 * @description: 读取cookie
 * @param {string} key
 * @return {*}
 */
export const getCookie = (key: string): string => {
    const cookieStr: string = unescape(document.cookie);
    const arr: string[] = cookieStr.split('; ');
    let cookieValue: string = '';
    for (let i = 0; i < arr.length; i++) {
        const temp = arr[i].split('=');
        if (temp[0] === key) {
            cookieValue = temp[1];
            break
        }
    }
    return cookieValue
};

/**
 * @description: 删除cookie
 * @param {string} key
 * @return {*}
 */
export const delCookie = (key: string) => {
    document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`
};